import { merge } from 'lodash'
import io from '@/utils/http/index.js'


const state = {
  list: [],

  // 选中看板
  selectedKanban: null
}

const actions = {
  
  getList ({ commit, state, dispatch }, payload) {
    return new Promise((resolve, reject) => {
      io({
        url: '/show/api/kanban'
      }).then(res => {
        commit('updated', res.data)
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },

  // 获取看板详情
  getKanbanDetails ({ commit, state, dispatch }, payload) {
    return new Promise((resolve, reject) => {
      io({
        url: '/show/api/kanban/' + payload || state.selectedKanban._id
      }).then(res => {
        if (res.data) {
          res.data.moduleList.forEach(o => {
            o.module.data = JSON.parse(o.module.data)
            o.module.apiConfig = o.module.apiConfig && JSON.parse(o.module.apiConfig)
            o.module.config = o.module.config && JSON.parse(o.module.config)
          })
        }
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },

  // 添加看板
  addKanban ({ commit, state, dispatch }, payload) {
    return new Promise((resolve, reject) => {
      io({
        url: '/show/api/kanban',
        method: 'post',
        data: payload
      }).then(res => {
        commit('unshift', res.data)
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  }
}

const getters = {
  
}

const mutations = {

  updated(state, payload) {
    state.list = payload
  },

  unshift (state, item) {
    state.list.unshift(item)
  },

  removeModule (state, moduleId) {
    const list = state.selectedKanban.moduleList
    const index = list.findIndex(o => o._id === moduleId)
    state.selectedKanban.moduleList.splice(index, 1)
  },


  setParams (state, payload) {
    if (payload) {
      for (let key in payload) {
        state[key] = payload[key]
      }
    }
  },

  // 设置看板图表的位置/大小
  setKanbanModule (state, payload) {
    if (state.selectedKanban && payload && payload.length) {
      payload.forEach(o => {
        let find = state.selectedKanban.moduleList.find(v => v._id === o.id)
        if (find) {
          find.x = o.x
          find.y = o.y
          find.w = o.w
          find.h = o.h
        }
      })

      const moduleList = state.selectedKanban.moduleList.map(o => {
        let obj = {module: o.module._id, _id: o._id}
        if (o.x !== undefined) {
          obj['x'] = o.x
        }
        if (o.y !== undefined) {
          obj['y'] = o.y
        }
        if (o.w !== undefined) {
          obj['w'] = o.w
        }
        if (o.h !== undefined) {
          obj['h'] = o.h
        }
        return obj
      })

      io({
        url: '/show/api/kanban/' + state.selectedKanban._id,
        method: 'put',
        data: {
          moduleList: moduleList
        }
      })
    }
  }
}

export default {
  strict: true,
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}